package com.xxxx.portal.interceptor;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xxxx.common.utils.CookieUtil;
import com.xxxx.common.utils.JsonUtil;
import com.xxxx.sso.pojo.Admin;
import com.xxxx.sso.service.IAdminService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


public class PortalInterceptor implements HandlerInterceptor {


    @Reference(version = "1.0")
    private IAdminService iAdminService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Value("${user.ticket}")
    private String userTicket;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //通过CookieUtil去拿用户票据
        String uTicket = CookieUtil.getCookieValue(request, "userTicket");

        if (!StringUtils.isBlank(uTicket)){
            //如果票据存在，则需要判断
            //获得用户的票
            Admin validate = iAdminService.validate(uTicket);
            //用户没有登录情况下，传过来的可能是个null
            if (null!=validate){
                //将票据存入session中，用于页面显示
                request.getSession().setAttribute("user", validate);
                System.out.println("validate==="+validate);
                //重写设置失效时间
                ValueOperations<String, String> operations = redisTemplate.opsForValue();
                operations.set(userTicket + ":" + uTicket, JsonUtil.object2JsonStr(validate), 30, TimeUnit.MINUTES);
                return true;
            }else{
                //票据过期了，需要重新获得票据
                request.getSession().removeAttribute("user");
            }
        }else {
            //票据过期了，需要重新获得票据
            request.getSession().removeAttribute("user");
        }

        //票据如果不存在或者登录失败就重定向到登录页面
        response.sendRedirect(request.getContextPath()+"/login");
        return  false;
    }


    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

